import type { SiteConfig, Menus } from '~/stores/interface'
import { cloneDeep } from 'lodash-es'

const editHeadNav = (navList: Menus[], subDomainPath: string): Menus[] => {
    for (const key in navList) {
        if (navList[key].path.includes(subDomainPath)) {
            if (navList[key].path === subDomainPath) {
                navList[key].path = '/'
            } else {
                navList[key].path = navList[key].path.replace(subDomainPath + '/', '')
            }
        }
        if (navList[key].children?.length) {
            navList[key].children = editHeadNav(navList[key].children, subDomainPath)
        }
    }
    // console.log(navList)
    return navList
}

export const getSubDomainSetting = (currentHost: string) => {
    try {
        const settings: Array<string[]> = JSON.parse(import.meta.env.VITE_SUBDOMAIN_RULES)

        const setting = settings.find((item) => item[0] === currentHost)
        if (setting?.length) {
            return {
                host: setting[0],
                subDomain: setting[1],
            }
        }
    } catch (error) {
        return null
    }

    return null
}

export const useSiteConfig = defineStore('siteConfig', {
    state: (): SiteConfig => {
        return {
            siteName: '',
            recordNumber: '',
            version: '',
            cdnUrl: '',
            apiUrl: '',
            upload: {
                mode: 'local',
                maxsize: 0,
                mimetype: '',
                savename: '',
            },
            headNavInner: [],
            initialize: false,
            userInitialize: false,
        }
    },
    getters: {
        headNav: (state): Menus[] => {
            const host = useNodeReqHost()

            const setting = getSubDomainSetting(host.value)
            if (setting) {
                return editHeadNav(cloneDeep(state.headNavInner), setting.subDomain)
            }

            return state.headNavInner
        },
    },
    actions: {
        dataFill(state: SiteConfig) {
            this.$state = { ...this.$state, ...state }
        },
        setHeadNav(headNav: Menus[]) {
            this.headNavInner = headNav
        },
        setInitialize(initialize: boolean) {
            this.initialize = initialize
        },
        setUserInitialize(userInitialize: boolean) {
            this.userInitialize = userInitialize
        },
    },
})
